<template>
	<view class="content">
		<view class="submit_type_exchanger">
			<button :class="{'active' : !submitLogin}" @click="submitLogin = false">注册</button>
			<button :class="{'active' : submitLogin}" @click="submitLogin = true">登录</button>
		</view>
		<form @submit="formSubmit">
			<view class="input_place">
				<input name="username" type="text" placeholder="请输入用户名" />
			</view>
			<view class="input_place">
				<input name="password" type="password" placeholder="请输入密码" />
			</view>
			<button form-type="submit">{{submitLogin ? "登录" : "注册"}}</button>
		</form>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				submitLogin: false
			}
		},
		methods: {
			formSubmit(e) {
				let form = e.detail.value
				var usernameRegex = /^[A-Za-z][A-Za-z0-9]{5,11}$/
				var passwordRegex = /^[A-Za-z0-9]{6,16}$/
				if (RegExp(usernameRegex).test(form.username) && RegExp(passwordRegex).test(form.password)) {
					if (this.submitLogin) {
						this.login(form)
					} else {
						this.register(form)
					}
				} else {
					this.showModal('用户名或密码输入错误')
				}
			},
			register(form) {
				uni.request({
					url: getApp().globalData.baseUrl + "auth/register",
					method: "PUT",
					data: form,
					success: function(result) {
						let data = result.data
						if(data.status == 200) {
							this.showModal('注册成功')
						} else {
							this.showModal(data.error)
						}
					}.bind(this)
				})
			},
			login(form) {
				uni.request({
					url: getApp().globalData.baseUrl + "auth/login",
					method: "POST",
					data: form,
					success: function(result) {
						let data = result.data
						if(data.status == 200) {
							this.showModal('登录成功\n用户名：'+data.data.username+'\n密码：'+data.data.password+'\nuuid：'+data.data.uuid)
						} else {
							this.showModal(data.error)
						}
					}.bind(this)
				})
			},
			showModal(text) {
				uni.showModal({
					showCancel: false,
					content: text
				})
			}
		}
	}
</script>

<style scoped>
	.content {
		margin: 0 auto;
		border: #333333 1px solid;
		box-shadow: black 3px 3px 4px;
	}

	.submit_type_exchanger {
		display: flex;
		flex-grow: 1;
	}

	.input_place {
		display: flex;
	}

	.submit_type_exchanger button {
		flex-grow: 1;
	}

	.submit_type_exchanger .active {
		color: #F1F1F1;
		background-color: #333333;
	}
</style>
